//
//  TKIMConverseView.m
//  TKIM
//
//  Created by liupm on 15/10/28.
//  Copyright © 2015年 liupm. All rights reserved.
//

#import "TKIMConverseView.h"
#import "TKIMConverseSearchView.h"
#import "TKIMConverseCell.h"
#import "TKIMSearchBar.h"
#import "TKIMRefreshHeaderView.h"

@interface TKIMConverseView()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchDisplayDelegate,UIActionSheetDelegate>

@property(nonatomic,strong) UILabel *headTip;
@property(nonatomic,strong) UIImageView *tipImage;

@property(nonatomic,strong) NSMutableArray *conversArray;
@property (nonatomic, strong) TKIMSearchBar  *searchBar;
@property(nonatomic,strong) TKIMConverseSearchView *searchController;
@property(nonatomic,strong) UIViewController *contentsController;
@property (nonatomic,strong)TKIMRefreshHeaderView * refreshHeader;

@property(nonatomic,strong) UIImageView *noMsg;

@end

@implementation TKIMConverseView

-(instancetype)initWithFrame:(CGRect)frame withDelegate:(id)delegate contentsController:(UIViewController *)ctl
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _contentsController = ctl;
        _delegate = delegate;
        _conversArray = [NSMutableArray array];
        [self drawView];
        [self refreshHeader];
    }
    return self;
}

/**
 *  @Author lpm, 15-10-28 17:10:29
 *
 *  @brief  绘制界面
 */
-(void)drawView
{

    //列表
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,44, self.frame.size.width, self.frame.size.height-44) style:UITableViewStylePlain];
    _tableView.dataSource  = self;
    _tableView.delegate = self;
    _tableView.rowHeight = 60;
    _tableView.separatorColor = [TKIMColorHelper stringToColor:@"#DCDCDC"];
    _tableView.separatorInset = UIEdgeInsetsZero;
    [_tableView setTableFooterView:[UIView new]];
    
    //无数据提示语
    _noMsg = [[UIImageView alloc] initWithFrame:CGRectMake((_tableView.frame.size.width-175)/2, (_tableView.frame.size.height-180)/2, 175, 90)];
    _noMsg.image = TKIMGetImage(@"nomsg@2x");
    
    [self addSubview:self.searchBar];
    [self addSubview:_tableView];
    [self searchController];
}


- (void)layoutSubviews
{
    [super layoutSubviews];
    _tableView.height = self.frame.size.height-44;
}


-(TKIMRefreshHeaderView *)refreshHeader
{
    __weak typeof(self) weakSelf = self;
    if (!_refreshHeader) {
        _refreshHeader = [[TKIMRefreshHeaderView alloc] initWithScrollView:weakSelf.tableView beginLoadMoreBlock:^(TKIMRefreshHeaderView * refreshHeader) {
            [TKIMSDKManager loadConversationsWithCountFromServer:^(NSInteger errorNumber, NSString *info) {
                if (errorNumber ==0) {
                     [weakSelf performSelector:@selector(sendRefreshNoti) withObject:nil];
                }
                [refreshHeader endRefresh];
                
            }];
        }];
    }
    return _refreshHeader;
}
-(void)sendRefreshNoti{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TKIMConverseView_headerRefresh" object:nil];
}

-(UIImageView *)headView
{
    if (!_headView)
    {
        _headView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _tableView.frame.size.width, 40)];
        _headView.backgroundColor = [TKIMColorHelper stringToColor:@"#FFF0B0"];
        [_headView addSubview:self.tipImage];
        [_headView addSubview:self.headTip];
        _headView.userInteractionEnabled = YES;
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, _headView.frame.size.height-0.5, _tableView.frame.size.width, 1.0f)];
        line.backgroundColor =[TKIMColorHelper stringToColor:@"#DCDCDC"];
        [_headView addSubview:line];
    }
    return _headView;
}


-(UILabel *)headTip
{
    if (!_headTip)
    {
        _headTip = [[UILabel alloc] initWithFrame:CGRectMake(self.tipImage.frame.size.width+self.tipImage.frame.origin.y, 0, _tableView.frame.size.width-40, 40)];
        _headTip.backgroundColor = [UIColor clearColor];
        _headTip.font = [UIFont systemFontOfSize:14.0f];
        _headTip.textColor = [UIColor blackColor];
    }
    return _headTip;
}


-(UIImageView *)tipImage
{
    if (!_tipImage)
    {
        _tipImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        _tipImage.image = TKIMGetImage(@"im_icon_fail");
        _tipImage.contentMode = UIViewContentModeCenter;

    }
    return _tipImage;
}


- (UISearchBar *)searchBar
{
    if (!_searchBar) {
        _searchBar = [[TKIMSearchBar alloc] initWithFrame: CGRectMake(0, 0, self.frame.size.width, 44)];
        _searchBar.delegate = self;
        _searchBar.placeholder = @"搜索";
        _searchBar.backgroundColor = [TKIMColorHelper stringToColor:@"#EFEFF4"];
        [_searchBar setTextFieldBackgroudColor:[UIColor whiteColor]];
        [_searchBar setCancelReturnKeyType: UIReturnKeyDone];
    }
    
    return _searchBar;
}

#pragma mark - UISearchBarDelegate


- (TKIMConverseSearchView *)searchController
{
    if (_searchController == nil)
    {
        _searchController = [[TKIMConverseSearchView alloc] initWithFrame:_tableView.frame searchBar:self.searchBar];
        _searchController.searchDelegate = _delegate;
    }
    return _searchController;
}



#pragma mark - Table view data source
/**
 *  @Author lpm, 15-10-21 10:10:39
 *
 *  @brief
 *
 *  @param tableView
 *
 *  @return
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

/**
 *  @Author lpm, 15-10-21 10:10:46
 *
 *  @brief
 *
 *  @param tableView
 *  @param section
 *
 *  @return
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _conversArray.count;
}


/**
 *  @Author lpm, 15-11-06 15:11:57
 *
 *  @brief
 *
 *  @param tableView
 *  @param indexPath
 *
 *  @return
 */

/*
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}}*/



////设置滑动时显示多个按钮
//- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
//    //添加一个删除按钮
//    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:(UITableViewRowActionStyleDestructive) title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath)
//                                          {
//                                              NSLog(@"点击了删除");
//                                              TKIMConverseMessage *msg = _conversArray[indexPath.row];
//                                              [[TKIMManager shareInstance] removeConverse:msg];
//                                              [_conversArray removeObject:msg];
//                                              [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//                                              if(_conversArray.count == 0)
//                                              {
//                                                  if (!_noMsg.superview)
//                                                  {
//                                                      [_tableView addSubview:_noMsg];
//                                                  }
//                                              }
//                                          }];
//    //删除按钮颜色
//    deleteAction.backgroundColor = [UIColor redColor];
//    
//    //添加一个置顶按钮
//    UITableViewRowAction *topRowAction =[UITableViewRowAction rowActionWithStyle:(UITableViewRowActionStyleDestructive) title:@"置顶" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
//        NSLog(@"点击了置顶");
//        TKIMConverseMessage *msg = _conversArray[indexPath.row];
//        //1.更新数据
//        [_conversArray exchangeObjectAtIndex:indexPath.row withObjectAtIndex:0];
//        //2.更新UI
//        NSIndexPath *firstIndexPath =[NSIndexPath indexPathForRow:0 inSection:indexPath.section];
//        [tableView moveRowAtIndexPath:indexPath toIndexPath:firstIndexPath];
//        
//        ////
//        [TKIMCacheHelper setValue:msg.targetUser forKey:@"top_target"];
//    }];
//    //置顶按钮颜色
//    topRowAction.backgroundColor = [UIColor orangeColor];
//    
//    //将设置好的按钮方到数组中返回
//    return @[deleteAction,topRowAction];
//    // return @[deleteAction,topRowAction,collectRowAction];
//}
//
///**
// *  @Author lpm, 15-11-06 15:11:02
// *
// *  @brief
// *
// *  @param tableView
// *  @param indexPath
// *
// *  @return
// */
//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (isCaiFuTong&&isCaiFuTongNeedStock) {
//        
//        if (indexPath.row<2) {
//            return NO;
//        }else{
//            return YES;
//        }
//    }else{
//    
//        return YES;
//    
//    }
//    
//
//}


/**
 *  @Author lpm, 15-11-06 15:11:08
 *
 *  @brief
 *
 *  @param tableView
 *  @param editingStyle
 *  @param indexPath
 */
/*
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    TKIMConverseMessage *msg = _conversArray[indexPath.row];
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        //删除会话
        [[TKIMManager shareInstance] removeConverse:msg];
        [_conversArray removeObject:msg];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        if(_conversArray.count == 0)
        {
            if (!_noMsg.superview)
            {
                [_tableView addSubview:_noMsg];
            }
        }
    }
}
*/

/**
 *  @Author lpm, 15-10-21 10:10:52
 *
 *  @brief
 *
 *  @param tableView
 *  @param indexPath
 *
 *  @return
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TKIMConverseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" ];
    
    if (!cell)
    {
        cell = [[TKIMConverseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    TKIMConverseMessage *msg = _conversArray[indexPath.row];
    cell.titleLabel.text = msg.targetUserName;
    cell.subLabel.text = msg.text;
    if (msg.text&&msg.text.length>0) {
       NSArray *b = [msg.text componentsSeparatedByString:@"|"];
        if (b&&b.count>0) {
          cell.subLabel.text = b[0];
        }
    }
    
   cell.contentView.backgroundColor = [UIColor whiteColor];
    if (isCaiFuTong&&isCaiFuTongNeedStock) {
        if(indexPath.row ==1 ) {
            cell.headView.image = [UIImage imageNamed:@"gupiaoyujing"];
            NSInteger msgCount = [TKIMCacheHelper integerForKey:TKIMSDK_GUJIAYUJING_MSGCOUNT];
            msg.msgCount = msgCount;
        }else if (indexPath.row==0){
            if (msg.isNeedOtherManage) {
                msg.msgCount = 0;
            }
        }
    }
    
    if (msg.chatUserType == TKIMUserTypeDefault || msg.chatUserType == TKIMUserTypeOfficial) {
        cell.headView.image = TKIMGetImage(@"im_icon_userDefault");
    } else if(msg.chatUserType == TKIMUserTypeSys) {
        
        NSString *url = @"";
        if (msg.photoUrl.length > 0) {
            url = msg.photoUrl;
            [self savePlistWithKey:msg.targetUserName value:msg.photoUrl];
        }else{
            url = [self getPlistWithKey:msg.targetUserName];
        }
        [cell.headView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:TKIMGetImage(@"IM_black_ic_sysMessage_0")];
        
//        [cell.headView sd_setImageWithURL:[NSURL URLWithString:msg.photoUrl] placeholderImage:TKIMGetImage(@"IM_black_ic_sysMessage_0")];
        
    }else{
        [cell.headView sd_setImageWithURL:[NSURL URLWithString:msg.photoUrl] placeholderImage:TKIMGetImage(@"IM_black_ic_sysMessage_0")];
    }
    
//    if ([msg.targetUser isEqualToString:@"gjyj"]) {
//        cell.headView.image = TKIMGetImage(@"im_icon_stockPriceWarn");
//    }else if([msg.targetUser isEqualToString:@"cash_change"]){
//        cell.headView.image = TKIMGetImage(@"im_icon_stockPriceWarn");
//    }
  
    cell.time.text = [TKIMDateHelper formattedTime:msg.time];
    [cell setMsgCount:msg.msgCount];
    cell.time.hidden=NO;
    return cell;
}


- (NSString *)getIconUrlPath
{
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [path objectAtIndex:0];
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"TKIMIconUrl.plist"];
    return plistPath;
}

- (void)savePlistWithKey:(NSString *)key value:(NSString *)value
{
    NSString *plistPath = [self getIconUrlPath];
    NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    
    if (!dataDict) {
        dataDict = [[NSMutableDictionary alloc]init];
    }
    
    [dataDict setObject:value forKey:key];
    [dataDict writeToFile:plistPath atomically:YES];
}

- (NSString *)getPlistWithKey:(NSString *)key
{
    NSString *plistPath = [self getIconUrlPath];
    NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    NSString *urlStr = [dataDict objectForKey:key];
    return urlStr;
}

/**
 *  @Author lpm, 15-10-21 10:10:57
 *
 *  @brief
 *
 *  @param tableView
 *  @param indexPath
 */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TKIMConverseMessage *msg = _conversArray[indexPath.row];
    
    if (isCaiFuTong&&isCaiFuTongNeedStock) {
        if(indexPath.row == 1){
            msg.msgCount = 0 ;
            [[NSNotificationCenter defaultCenter] postNotificationName:MESSAGE_ITEM_CLICK object:nil userInfo:@{@"msg" : @"股价预警"}];
            return ;
        }else if (indexPath.row==0){
            if (msg.isNeedOtherManage) {
                 [self OnShowPhoneList:nil];
                return ;
            }
        }
    }
    
    if (msg.chatUserType != TKIMUserTypeRoom && msg.chatUserType != TKIMUserTypeGroup)
    {
        TKIMUser *user = [[TKIMUser alloc] init];
        user.userID = msg.targetUser;
        user.nickName = msg.targetUserName;
        user.isToTop = msg.isToTop;
        user.userType = msg.chatUserType;
        if (_delegate &&[_delegate respondsToSelector:@selector(toChat:converse:)])
        {
            [_delegate toChat:user converse:msg];
        }
    }
    else
    {
        TKIMRoom *group = [[TKIMRoom alloc] init];
        group.roomName = msg.targetUserName;
        group.roomId = msg.targetUser;
        group.isToTop = msg.isToTop;
        group.roomType = msg.chatUserType;
        if (_delegate &&[_delegate respondsToSelector:@selector(toGroup:)])
        {
            [_delegate toGroup:group];
        }
    }
}


- (void)OnShowPhoneList:(NSString*)telphone
{
    UIActionSheet *contactAlert = nil;
    if(telphone == nil || [telphone length] <=0 )
        telphone = @"95358";
    contactAlert = [[UIActionSheet alloc] initWithTitle:@"拨打电话"
                                               delegate:self
                                      cancelButtonTitle:@"取消"
                                 destructiveButtonTitle:nil
                                      otherButtonTitles:telphone,nil];
    
    // use the same style as the nav bar
    contactAlert.actionSheetStyle = UIActionSheetStyleDefault;
    [contactAlert showInView:[UIApplication sharedApplication].keyWindow];
    
}

- (void)actionSheet:(UIActionSheet *)modalView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch ( buttonIndex )
    {
        case 0:
        {
            NSString *telStr = [[NSString alloc] initWithFormat:@"tel:%@",@"95358"];
            NSString *strUrl = [telStr stringByAddingPercentEscapesUsingEncoding:NSMacOSRomanStringEncoding];
            NSURL *telURL = [[NSURL alloc] initWithString:strUrl];
            [[UIApplication sharedApplication] openURL:telURL];
        }
            break;
        case 1:
            break;
        default:
            break;
    }
}

/**
 *  @Author lpm, 15-10-30 17:10:05
 *
 *  @brief  刷新头
 *
 *  @param txt
 */
-(void)reloadHead:(NSString *)txt
{
    if (![TKIMSDKManager isNotTips]) {
        if ([txt isEqualToString:@""])
        {
            if ([self.headView superview])
            {
                [self.headView removeFromSuperview];
                [_tableView setTableHeaderView:nil];
            }
        }
        else
        {
            if (![self.headView superview])
            {
                [_tableView setTableHeaderView:self.headView];
            }
        }
        self.headTip.text = txt;
        
    }
    

}


/**
 *  @Author lpm, 15-10-30 17:10:31
 *
 *  @brief  刷新数据
 *
 *  @param array
 */
-(void)reloadData:(NSMutableArray *)array
{
    if(array)
    {
        if(array.count >0)
        {
            if (_noMsg.superview)
            {
                [_noMsg removeFromSuperview];
            }
        }
        else
        {
            if (!_noMsg.superview)
            {
                [_tableView addSubview:_noMsg];
            }
        }
        
        _conversArray = array;
        
        ////
        NSString* top_target = [TKIMCacheHelper valueForKey:@"top_target"];
        int i = 0;
        for(TKIMConverseMessage* msg in _conversArray){
            if(msg  && [top_target isEqualToString:msg.targetUser] && i >0){
                [array exchangeObjectAtIndex:i withObjectAtIndex:0];
                break;
            }
            ++i;
        }
        
        if (isCaiFuTong&&isCaiFuTongNeedStock) {
            TKIMConverseMessage *msg = nil;
            if(_conversArray.count>0)
            {
                msg = [[TKIMConverseMessage alloc]init];
                msg.msgCount = 0;
                msg.targetUser = @"股价预警";
                msg.targetUserName =  @"股价预警";
                msg.isTempSession = NO;
                msg.isRemind = NO;
                msg.isNeedOtherManage = YES;
                msg.text = @"股价预警";
                [_conversArray insertObject:msg atIndex:1];
            }
        }
        [_tableView reloadData];
    }
    else
    {
        if (!_noMsg.superview)
        {
            [_tableView addSubview:_noMsg];
        }
    }
}

- (void)cleanRedDot:(NSString *)dotType
{
    if (_conversArray.count > 0) {
        for (NSInteger i = 0; i < _conversArray.count; i++) {
            TKIMConverseMessage *msg = _conversArray[i];
            if ([msg.targetUser isEqualToString:dotType]) {
                msg.msgCount = 0;
                NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:0];
                NSArray *arr = @[path];
                [self.tableView reloadRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationNone];
                [[TKIMDBManager shareInstance] updateConvserCount:msg];
            }
        }
    }
}

@end
